package com.caigou.listener;

import com.caigou.constant.NewsConstant;
import com.caigou.service.SystemMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Resource
    private SystemMessageService systemMessageService;
    /**
     * 针对 redis 数据失效事件，进行系统消息等自动发布处理
     * @param message
     * @param pattern
     */
    public void onMessage(Message message, byte[] pattern) {
        // 获取到失效的key，进行系统消息发布功能
        String expiredKey = message.toString();
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (expiredKey.startsWith(NewsConstant.SYSTEM_MESSAGE_PRE_KEY)) {
            log.info("收到了已经消失的 key = {},接收的时间为 {}", expiredKey, format.format(date));
            autoPublishSystemMessage(expiredKey);
        }
    }

    private void autoPublishSystemMessage(String expiredKey){
        String[] arr = expiredKey.split(":");
        if(arr.length!=2){
            log.warn("expiredKey={}长度错误", expiredKey);
            return;
        }
        int id = Integer.parseInt(arr[1]);
        int count = systemMessageService.autoPublishSystemMessage(id);
        if(count>0){
            log.info("系统消息定时发布成功，id={}, expiredKey={}", id, expiredKey);
        }else{
            log.warn("系统消息定时发布失败，id={}, expiredKey={}", id, expiredKey);
        }
    }
}